package com.zlsoft.web;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.webkit.JavascriptInterface;

import androidx.activity.result.ActivityResultLauncher;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.journeyapps.barcodescanner.ScanOptions;
import com.lxj.xpopup.XPopup;
import com.zlsoft.web.sp.ConfigPreference;
import com.zlsoft.web.ui.activity.MainActivity;
import com.zlsoft.web.utils.QrUtils;
import com.zlsoft.web.utils.UpdateManager;
import com.zlsoft.web.utils.X5WebView;

import java.io.IOException;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.schedulers.Schedulers;

/***
 *@author QQz
 *@description:
 *@date : 2021/10/21 15:29
 */
public class AndroidInterface {

    private static AndroidInterface androidInterface;

    public static AndroidInterface getInstance(MainActivity activity, X5WebView mWebView, SwipeRefreshLayout swipeRefreshLayout, ActivityResultLauncher<ScanOptions> barcodeLauncher) {
        if (androidInterface == null) {
            androidInterface = new AndroidInterface(activity, mWebView, barcodeLauncher);
        }
        return androidInterface;
    }


    private MainActivity mActivity;

    private X5WebView mWebView;


    private ActivityResultLauncher<ScanOptions> mBarcodeLauncher;


    public AndroidInterface(MainActivity activity, X5WebView mWebView, ActivityResultLauncher<ScanOptions> barcodeLauncher) {
        this.mActivity = activity;
        this.mWebView = mWebView;
        this.mBarcodeLauncher = barcodeLauncher;
    }

    /**
     * @param optionType 1 条形码 2二维码
     * @return state
     */
    @JavascriptInterface
    public void startScanQR(int optionType) {
        if (optionType == 1) {
            ScanOptions options = new ScanOptions();
            options.setCaptureActivity(AnyOrientationCaptureActivity.class);
            options.setDesiredBarcodeFormats(ScanOptions.ONE_D_CODE_TYPES);
            options.setPrompt("请对准[条形码]扫描");
            options.setCameraId(0);
            options.setBeepEnabled(false);
            options.setOrientationLocked(false);
            options.setBarcodeImageEnabled(true);
            QrUtils.getInstance().QrProduct(mActivity, QrUtils.HW_SCAN_FOR_RESULT_WEB_CODE);
        }

        if (optionType == 2) {
            QrUtils.getInstance().QrProduct(mActivity, QrUtils.HW_SCAN_FOR_RESULT_WEB_CODE);
        }
    }

    /**
     * @return
     */
    @JavascriptInterface
    public String resetWebPath() {
        QrUtils.getInstance().QrProduct(mActivity, QrUtils.HW_SCAN_FOR_REST_WEB_RESULT_WEB_CODE);
        return "ok";
    }


    @JavascriptInterface
    public void loadWeb(String url) {
        mWebView.loadUrl(url);
    }

    /**
     *
     */
    @JavascriptInterface
    public void cleanCache() {
        new XPopup.Builder(mActivity).asConfirm("提示", "该操作会清除应用所有缓存,是否继续?", () -> {
            ActivityManager manager = (ActivityManager) mActivity.getSystemService(Context.ACTIVITY_SERVICE);
            manager.clearApplicationUserData();
        }).show();
    }


    @JavascriptInterface
    public void android() {
        Observable.just("").subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(mS -> {
            mWebView.evaluateJavascript("javaCallJs()", null);
        });
    }

    /**
     * @return
     */
    @JavascriptInterface
    public String getConfig() {
        try {
            return ConfigPreference.getInstance().getConfig();
        } catch (IOException mE) {
            mE.printStackTrace();
        }
        return "获取失败,配置信息有误";
    }

    /**
     * @param json
     * @return
     */
    @JavascriptInterface
    public String setConfig(String json) {
        try {
            ConfigPreference.getInstance().setConfig(json);
        } catch (IOException mE) {
            return "设置失败,配置信息有误";
        }
        return "ok";
    }

    /**
     * @param params
     * @return
     */
    @JavascriptInterface
    public String checkUpdate(String params) {
        if (params == null) {
            return "missing required parameter";
        }
        UpdateManager.cInit(mActivity, params);
        return "ok";
    }

    /**
     * 获取app 版本code
     *
     * @return
     */
    @JavascriptInterface
    public String getVersionCode() {
        try {
            PackageInfo packageInfo = mActivity.getApplicationContext().getPackageManager().getPackageInfo(mActivity.getPackageName(), 0);
            return packageInfo.versionCode + "";
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    @JavascriptInterface
    public String getVersionName() {
        try {
            PackageInfo packageInfo = mActivity.getApplicationContext().getPackageManager().getPackageInfo(mActivity.getPackageName(), 0);
            return packageInfo.versionName + "";
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 下载apk
     *
     * @param url
     * @return
     */
    @JavascriptInterface
    public String downloadApk(String url) {
        UpdateManager.downloadApp(mActivity, url);
        return "ok";
    }


}
